package edu.usm.cs.roberge;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class NewsGroup implements Serializable {
	
	private static final long serialVersionUID = 1L;
	
	private final String newsGroupName;
	private final String startMessage;
	private final String endMessage;
	private final List<Message> messages = new ArrayList<Message>();
	private final boolean isPostable;
	private boolean favorite;
	
	public NewsGroup(String newsGroupName, String startMessage, String endMessage, boolean isPostable) {
		this.newsGroupName = newsGroupName;
		this.startMessage = startMessage;
		this.endMessage = endMessage;
		this.isPostable = isPostable;
	}

	public String getNewsGroupName() {
		return newsGroupName;
	}

	public String getStartMessage() {
		return startMessage;
	}

	public String getEndMessage() {
		return endMessage;
	}
	
	public boolean isFavorite() {
		return favorite;
	}

	public void setFavorite(boolean favorite) {
		this.favorite = favorite;
	}

	@Override public String toString() {
		return "Group name: " + newsGroupName + ", startMessage: " + startMessage + ", endMessage: " 
		+ endMessage + ", postable: " + isPostable;
		
	}

	public static NewsGroup parseFromString(String line) {
		String[] tokens = line.split(" ");
		if (tokens.length != 4) {
			// return an empty NewsGroup
			return new NewsGroup("", "", "", false);
		}
		
		String groupName = tokens[0];
		String startMessage = "", endMessage = "";
		try {
			endMessage = tokens[1];
			startMessage = tokens[2];
		} catch (NumberFormatException e) {
			
		}
		
		boolean postable = false;
		if (tokens[3].equals("y")) {
			postable = true;
		}
		
		return new NewsGroup(groupName, startMessage, endMessage, postable);
	}

	public int getMessageCount() {
		int start = Integer.parseInt(startMessage);
		int end = Integer.parseInt(endMessage);
		
		if (start > end) {
			return 0; // as per specification
		}
		
		return end - start;
	}

	public void addMessage(Message msg) {
		messages.add(msg);
	}

	public boolean hasAllMessages() {
		return messages.size() >= 10;
	}

	public List<Message> getAllMessages() {
		return messages;
	}

}
